"use client";
import { DepositsTypes, RewardsType } from "@/api/depositsApi";
import { getUserRechargeApi } from "@/api/user";
import Box from "@/components/Box";
import { useUserInfoStore } from "@/stores/useUserInfoStore";
import { neReg } from "@/utils";
import { Form, Input, Toast } from "antd-mobile";
import { FormInstance } from "antd-mobile/es/components/form";
import { useTranslations } from "next-intl";
import { FC, Fragment, useLayoutEffect, useRef, useState } from "react";

import ButtonOwn from "@/components/ButtonOwn";
import "@/styles/deposit.scss";
import { server } from "@/utils/client";
import Image from "next/image";
interface Props {
    deposits: DepositsTypes[];
}

interface RewardsProps {
    rewards: RewardsType[];
}
const RewardsText: FC<RewardsProps> = (props) => {
    const { rewards } = props;
    // {/*1现金2彩金3免费币4重玩币*/}
    const t = useTranslations();
    const calcRewards = rewards
        .map((item) => {
            // 根据coin_type添加后缀
            const suffixes = {
                1: t("ProfilePage.balance"),
                2: t("ProfilePage.balance"),
                3: t("ProfilePage.free"),
                4: t("ProfilePage.replay"),
            };
            let text = "";
            // 设置基础奖励文本
            if (item.ratio > 0) {
                text = `${item.ratio}`;
            } else {
                text = `${item.reward}`;
            }
            if (item.ratio > 0 && item.reward > 0) {
                text = `${item.ratio}%${suffixes[item.coin_type]}, ${item.reward}`;
            }

            // 如果coin_type在suffixes中存在，则添加相应的后缀
            if (suffixes.hasOwnProperty(item.coin_type)) {
                text += suffixes[item.coin_type];
            }

            return text;
        })
        .join(",");

    return (
        <div className={"flex flex-1 flex-wrap break-all"}>
            <span className="amountTips">+ {calcRewards} </span>
        </div>
    );
};

const getDepositApi = async () => {
    return server
        .request<DepositsTypes[]>({
            url: "/v1/api/user/user_deposit_config",
            method: "post",
            data: { activity_type: 2 },
        })
        .then((res) => {
            if (res.code === 200) return res.data;
            return [];
        });
};
const DepositData: FC<Props> = (props) => {
    // const { deposits } = props;
    const t = useTranslations();
    const userInfo = useUserInfoStore((state) => state.userInfo);

    // 选中类型

    const [depositState, setDepositState] = useState<DepositsTypes[]>([]);
    const [activeType, setActiveType] = useState<Partial<DepositsTypes>>({});
    const count = activeType.num || 0;

    const formInstanceRef = useRef<FormInstance>(null);
    let [amount, setAmount] = useState<number | undefined>(undefined);
    const titleChangeHandler = (item: DepositsTypes, index: number) => {
        setAmount(undefined);
        setActiveType(item);
        formInstanceRef.current?.resetFields();
    };

    const isStrictMode = true;

    const onFinish = (values: any) => {
        const params = { ...values, channel_id: activeType.id, amount: +values.amount };
        getUserRechargeApi(params)
            .then(async (res) => {
                formInstanceRef.current?.resetFields();
                Toast.show({ icon: "success", content: t("code.200"), maskClickable: false });
                setAmount(undefined);

                const data = await getDepositApi();
                setDepositState(data);
                setActiveType(data[0]);
                if (res.data.pay_url) {
                    window.open(res.data.pay_url);
                }
            })
            .catch((error) => {
                Toast.show({ content: t(`code${error.data.code}`), maskClickable: false });
            });
    };
    const onValuesChange = (changeValues: any) => {
        if (changeValues.amount) {
            setAmount(changeValues.amount);
        }
    };
    const amountChange = (value: number) => {
        formInstanceRef.current?.setFieldValue("amount", value);
        setAmount(value);
    };
    const amountValidator = (rules: any, value: any) => {
        if (!value) return Promise.reject(new Error(t("form.amount")));
        if (+value < activeType.min_amount!)
            return Promise.reject(
                new Error(t("form.amountMinReg", { amount: activeType.min_amount }))
            );
        if (+value > activeType.max_amount!)
            return Promise.reject(
                new Error(t("form.amountMaxReg", { amount: activeType.max_amount }))
            );
        return Promise.resolve();
    };

    useLayoutEffect(() => {
        getDepositApi().then((data) => {
            setDepositState(data);
            setActiveType(data[0]);
        });
    }, []);

    return (
        <>
            <Image src={"/doings/recharge.jpg"} alt={"deposit"} width={1950} height={10} />
            <div className="deposit-box">
                <div className={"flex items-center"}>
                    <div className="img-box"></div>
                    <div className={"flex-1 text-right"}>
                        <i
                            className={"iconfont icon-star_full text-[0.15rem] text-primary-color"}
                        ></i>
                        {`{${count}} recargas restantes`}
                    </div>
                </div>

                <div className={"flex flex-wrap"}>
                    {depositState.map((item, index) => {
                        return (
                            <Fragment key={item.id}>
                                <p
                                    className="btn-box truncate"
                                    style={{
                                        borderColor: activeType.id === item.id ? "#ff9323" : "#333",
                                    }}
                                    onClick={() => titleChangeHandler(item, index)}
                                >
                                    {item.name}
                                </p>
                            </Fragment>
                        );
                    })}
                </div>

                <Box className={"custom-form"} style={{ padding: 0 }}>
                    <Form
                        style={{
                            "--border-bottom": "none",
                            "--border-top": "none",
                            "--border-inner": "none",
                        }}
                        ref={formInstanceRef}
                        initialValues={userInfo}
                        onFinish={onFinish}
                        onValuesChange={onValuesChange}
                        footer={
                            <>
                                <ButtonOwn active>{t("DepositPage.DepositarAgora")}</ButtonOwn>
                            </>
                        }
                    >
                        {isStrictMode ? (
                            <>
                                <Form.Item
                                    name="user_name"
                                    label=""
                                    rules={[{ required: true, message: t("form.usernameReg") }]}
                                >
                                    <Input placeholder={t("form.username")} />
                                </Form.Item>
                                <Form.Item
                                    name="passport"
                                    label=""
                                    rules={[
                                        {
                                            required: true,
                                            message: t("form.cardReg"),
                                            pattern: neReg,
                                        },
                                    ]}
                                >
                                    <Input
                                        placeholder={t("form.card")}
                                        maxLength={11}
                                        type={"text"}
                                    />
                                </Form.Item>
                            </>
                        ) : null}
                        <Form.Item
                            name="amount"
                            label=""
                            rules={[{ required: true, type: "number", validator: amountValidator }]}
                        >
                            <Input
                                placeholder={`${t("DepositPage.Montante")}(BRL): Mín. ${activeType.min_amount}`}
                                type={"number"}
                                maxLength={activeType.max_amount}
                            />
                        </Form.Item>

                        <div className={"flex flex-col"}>
                            <div className={"flex-1"}>
                                <ul className="ul-box">
                                    {activeType?.products?.map((item, index) => (
                                        <li
                                            className={amount == item.amount ? "active" : ""}
                                            key={index}
                                            onClick={() => amountChange(item.amount)}
                                        >
                                            {!!item.badge && <span className="hot"></span>}
                                            <div className="amountContent">
                                                {/* <span className="iconfont icon-unit-brl"></span> */}
                                                <span className="iconfont">R$</span>
                                                <span> {item.amount}</span>
                                            </div>
                                            <div className={"flex"}>
                                                {item.rewards && (
                                                    <RewardsText rewards={item.rewards} />
                                                )}
                                            </div>

                                            {/*<span className="amountTips">*/}
                                            {/*    {t("DepositPage.Oferecer")} 100%*/}
                                            {/*</span>*/}
                                        </li>
                                    ))}
                                </ul>
                            </div>
                        </div>
                    </Form>
                </Box>
                <p className={"text-[#e59c5f]"}>Descrição daatividade:</p>
                <p className={"text-[0.12rem] text-[#e59c5f]"}>
                    Recarregue nas primeiras {`{${count}}`} vezes todos os dias e ganhe desco
                </p>
            </div>
        </>
    );
};

export default DepositData;
